package com.seven.springcloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author com.seven
 * @Date 2020/4/22 15:46
 * @Component:使得容器能够扫描的到
 **/
@Component
@Slf4j
public class MyRoundRobinRule implements LoadBalancer {

    /**
     * 使用原子整形来保证正确的来轮询（值统一）
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        //当前值
        int current;
        //下一个值
        int next;
        //自旋锁,退出条件:当next=current+1则跳出
        do {
            current = this.atomicInteger.get();
            //先判断是否超界了，防止报错（代码严谨：要做到他想到的你要想到，他想不到的也要想到）
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        log.info("=====>next的值："+next);
        return next;
    }

    @Override
    public ServiceInstance INSTANCE(List<ServiceInstance> serviceInstances) {
        //获得当前的service索引
        int index =getAndIncrement()% serviceInstances.size();
        //返回选择出来的service
        return serviceInstances.get(index);
    }
}
